const express = require('express');
const router = express.Router();
const { query } = require('../config/database');
const { authenticateToken, requireAdmin, optionalAuth } = require('../middleware/auth');
const { validatePagination, validateId } = require('../middleware/validation');
const ResponseHelper = require('../utils/response');
const { calculatePagination } = require('../utils/helpers');

// 验证公告数据
const validateAnnouncement = (req, res, next) => {
  const { title, content, type } = req.body;
  
  if (!title || title.trim().length === 0) {
    return ResponseHelper.error(res, '公告标题不能为空', 400);
  }
  
  if (!content || content.trim().length === 0) {
    return ResponseHelper.error(res, '公告内容不能为空', 400);
  }
  
  if (!type || !['notice', 'promotion', 'maintenance', 'event'].includes(type)) {
    return ResponseHelper.error(res, '公告类型无效', 400);
  }
  
  next();
};

// 获取公告列表
router.get('/', optionalAuth, validatePagination, async (req, res) => {
  try {
    const { page, pageSize, offset, limit } = calculatePagination(req.query.page, req.query.pageSize);
    const { type, status, search } = req.query;

    // 构建查询条件
    let whereClause = 'WHERE 1=1';
    let queryParams = [];

    // 非管理员只能看到已发布的公告
    if (!req.user || req.user.role !== 'admin') {
      whereClause += ' AND status = ?';
      queryParams.push('published');
    }

    if (type) {
      whereClause += ' AND type = ?';
      queryParams.push(type);
    }

    if (status && req.user && req.user.role === 'admin') {
      whereClause += ' AND status = ?';
      queryParams.push(status);
    }

    if (search) {
      whereClause += ' AND (title LIKE ? OR content LIKE ?)';
      const searchPattern = `%${search}%`;
      queryParams.push(searchPattern, searchPattern);
    }

    // 获取公告总数
    const countResult = await query(
      `SELECT COUNT(*) as total FROM announcements ${whereClause}`,
      queryParams
    );
    const total = countResult[0].total;

    // 获取公告列表
    const announcements = await query(
      `SELECT id, title, content, type, status, priority, publish_time, created_at, updated_at
       FROM announcements
       ${whereClause}
       ORDER BY priority DESC, publish_time DESC, created_at DESC
       LIMIT ? OFFSET ?`,
      [...queryParams, limit, offset]
    );

    ResponseHelper.success(res, {
      announcements,
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize)
      }
    }, '获取公告列表成功');

  } catch (error) {
    console.error('获取公告列表错误:', error);
    ResponseHelper.serverError(res, '获取公告列表失败');
  }
});

// 获取最新公告
router.get('/latest', async (req, res) => {
  try {
    const { limit = 6 } = req.query;
    
    const announcements = await query(
      `SELECT id, title, content, type, priority, publish_time
       FROM announcements
       WHERE status = 'published'
       ORDER BY priority DESC, publish_time DESC
       LIMIT ?`,
      [parseInt(limit)]
    );

    ResponseHelper.success(res, announcements, '获取最新公告成功');

  } catch (error) {
    console.error('获取最新公告错误:', error);
    ResponseHelper.serverError(res, '获取最新公告失败');
  }
});

// 获取公告详情
router.get('/:id', optionalAuth, validateId, async (req, res) => {
  try {
    const announcementId = req.params.id;

    let whereClause = 'WHERE id = ?';
    let queryParams = [announcementId];

    // 非管理员只能看到已发布的公告
    if (!req.user || req.user.role !== 'admin') {
      whereClause += ' AND status = ?';
      queryParams.push('published');
    }

    const announcements = await query(
      `SELECT id, title, content, type, status, priority, publish_time, created_at, updated_at
       FROM announcements
       ${whereClause}`,
      queryParams
    );

    if (announcements.length === 0) {
      return ResponseHelper.notFound(res, '公告不存在');
    }

    ResponseHelper.success(res, announcements[0], '获取公告详情成功');

  } catch (error) {
    console.error('获取公告详情错误:', error);
    ResponseHelper.serverError(res, '获取公告详情失败');
  }
});

// 创建公告（管理员）
router.post('/', authenticateToken, requireAdmin, validateAnnouncement, async (req, res) => {
  try {
    const { title, content, type, priority = 0, status = 'draft' } = req.body;
    const created_by = req.user.id;

    const result = await query(
      `INSERT INTO announcements (title, content, type, priority, status, created_by, created_at, updated_at)
       VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())`,
      [title, content, type, priority, status, created_by]
    );

    // 如果状态是已发布，设置发布时间
    if (status === 'published') {
      await query(
        'UPDATE announcements SET publish_time = NOW() WHERE id = ?',
        [result.insertId]
      );
    }

    ResponseHelper.success(res, { id: result.insertId }, '创建公告成功');

  } catch (error) {
    console.error('创建公告错误:', error);
    ResponseHelper.serverError(res, '创建公告失败');
  }
});

// 更新公告（管理员）
router.put('/:id', authenticateToken, requireAdmin, validateId, validateAnnouncement, async (req, res) => {
  try {
    const announcementId = req.params.id;
    const { title, content, type, priority, status } = req.body;

    // 检查公告是否存在
    const existingAnnouncements = await query('SELECT id, status FROM announcements WHERE id = ?', [announcementId]);
    if (existingAnnouncements.length === 0) {
      return ResponseHelper.notFound(res, '公告不存在');
    }

    const oldStatus = existingAnnouncements[0].status;

    // 更新公告
    await query(
      `UPDATE announcements 
       SET title = ?, content = ?, type = ?, priority = ?, status = ?, updated_at = NOW()
       WHERE id = ?`,
      [title, content, type, priority, status, announcementId]
    );

    // 如果状态从非发布变为发布，设置发布时间
    if (oldStatus !== 'published' && status === 'published') {
      await query(
        'UPDATE announcements SET publish_time = NOW() WHERE id = ?',
        [announcementId]
      );
    }

    ResponseHelper.success(res, null, '更新公告成功');

  } catch (error) {
    console.error('更新公告错误:', error);
    ResponseHelper.serverError(res, '更新公告失败');
  }
});

// 发布公告（管理员）
router.put('/:id/publish', authenticateToken, requireAdmin, validateId, async (req, res) => {
  try {
    const announcementId = req.params.id;

    // 检查公告是否存在
    const existingAnnouncements = await query('SELECT id FROM announcements WHERE id = ?', [announcementId]);
    if (existingAnnouncements.length === 0) {
      return ResponseHelper.notFound(res, '公告不存在');
    }

    // 发布公告
    await query(
      'UPDATE announcements SET status = ?, publish_time = NOW(), updated_at = NOW() WHERE id = ?',
      ['published', announcementId]
    );

    ResponseHelper.success(res, null, '发布公告成功');

  } catch (error) {
    console.error('发布公告错误:', error);
    ResponseHelper.serverError(res, '发布公告失败');
  }
});

// 取消发布公告（管理员）
router.put('/:id/unpublish', authenticateToken, requireAdmin, validateId, async (req, res) => {
  try {
    const announcementId = req.params.id;

    // 检查公告是否存在
    const existingAnnouncements = await query('SELECT id FROM announcements WHERE id = ?', [announcementId]);
    if (existingAnnouncements.length === 0) {
      return ResponseHelper.notFound(res, '公告不存在');
    }

    // 取消发布公告
    await query(
      'UPDATE announcements SET status = ?, updated_at = NOW() WHERE id = ?',
      ['draft', announcementId]
    );

    ResponseHelper.success(res, null, '取消发布公告成功');

  } catch (error) {
    console.error('取消发布公告错误:', error);
    ResponseHelper.serverError(res, '取消发布公告失败');
  }
});

// 删除公告（管理员）
router.delete('/:id', authenticateToken, requireAdmin, validateId, async (req, res) => {
  try {
    const announcementId = req.params.id;

    // 检查公告是否存在
    const existingAnnouncements = await query('SELECT id FROM announcements WHERE id = ?', [announcementId]);
    if (existingAnnouncements.length === 0) {
      return ResponseHelper.notFound(res, '公告不存在');
    }

    // 删除公告
    await query('DELETE FROM announcements WHERE id = ?', [announcementId]);

    ResponseHelper.success(res, null, '删除公告成功');

  } catch (error) {
    console.error('删除公告错误:', error);
    ResponseHelper.serverError(res, '删除公告失败');
  }
});

module.exports = router;
